package com.fivestar.finance.library.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 时间工具类
 */
@SuppressLint("SimpleDateFormat")
public final class DateUtil {

    public static final SimpleDateFormat FORMAT_DATE = new SimpleDateFormat("yyyyMMdd");

    /**
     * 2015/02/04
     */
    public static final String FORMAT_DATE_YYYY_MM_DD = "yyyy-MM-dd";

    /**
     * 2015-02-05T10:56:20.293
     */
    public static final String FORMAT_DATE_YYYYMMDD_T_HHMMSSSSS = "yyyy-MM-ddHH:mm:ss.SSS";

    /**
     * 2015-02-05T10:56:20
     */
    public static final String FORMAT_DATE_YYYYMMDD_T_HHMMSS = "yyyy-MM-dd HH:mm:ss";

    /**
     * 2015-02-05 10:56
     */
    public static final String FORMAT_DATE_YYYYMMDD_T_HHMM = "yyyy-MM-dd HH:mm";


    public final static ThreadLocal<SimpleDateFormat> dateFormater1 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_DATE_YYYY_MM_DD);
        }
    };
    public final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_DATE_YYYYMMDD_T_HHMM);
        }
    };

    public final static ThreadLocal<SimpleDateFormat> dateFormater3 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_DATE_YYYYMMDD_T_HHMMSS);
        }
    };

    private DateUtil() {
    }

    /**
     * 返回当前系统时间（"yyyyMMdd"）
     *
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getCurrentTime() {
        return FORMAT_DATE.format(new Date());
    }

    /**
     * 返回当前系统时间
     *
     * @param format
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getCurrentTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }

    /**
     * <获取两天的相差日期>
     * <时间格式为yyyyMMdd>
     *
     * @param begin :开始时间
     * @param end   ：结束时间
     * @return 天
     * @see [类、类#方法、类#成员]
     */
    public static long getDifferTime(String begin, String end) {
        long day = 0;
        try {
            Date beginDate = FORMAT_DATE.parse(begin);
            Date endDate = FORMAT_DATE.parse(end);
            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            day = 0;
        }
        return day;
    }

    /**
     * <功能详细描述>
     *
     * @param format
     * @param dateStr
     * @param resultFormat
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getFormatDate(String format, String dateStr, String resultFormat) {
        if (TextUtils.isEmpty(dateStr)) {
            return "";
        }
        String temp = "";
        if (dateStr.contains("T")) {
            temp = dateStr.replace("T", " ");
        } else {
            temp = dateStr;
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat(format); // 实例化模板对象    
        SimpleDateFormat sdf2 = new SimpleDateFormat(resultFormat); // 实例化模板对象    
        Date d = null;
        try {
            d = sdf1.parse(temp); // 将给定的字符串中的日期提取出来    
        } catch (Exception e) {
            return "";
        }
        return sdf2.format(d);// 将日期变为新的格式  
    }

    public static String getFileName() {
        String date = FORMAT_DATE.format(new Date(System.currentTimeMillis()));
        return date;
    }

    public static String getDateEN() {
        SimpleDateFormat format1 = new SimpleDateFormat(FORMAT_DATE_YYYYMMDD_T_HHMMSSSSS, Locale.getDefault());
        String date1 = format1.format(new Date(System.currentTimeMillis()));
        return date1;
    }

    public static String getDate(long date, String format) {
        SimpleDateFormat format1 = new SimpleDateFormat(format, Locale.getDefault());
        String date1 = format1.format(new Date(date));
        return date1;
    }


    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendlyTime(String sdate) {
        Date time = null;

        if (isInEasternEightZones()) {
            time = toDate(sdate);
        } else {
            time = transformTime(toDate(sdate), TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());
        }

        if (time == null) {
            return sdate;
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater3.get().format(cal.getTime());
        String paramDate = dateFormater3.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天 ";
        } else if (days > 2 && days < 31) {
            ftime = days + "天前";
        } else if (days >= 31 && days <= 2 * 31) {
            ftime = "一个月前";
        } else if (days > 2 * 31 && days <= 3 * 31) {
            ftime = "2个月前";
        } else if (days > 3 * 31 && days <= 4 * 31) {
            ftime = "3个月前";
        } else {
            ftime = dateFormater3.get().format(time);
        }
        return ftime;
    }

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        return toDate(sdate, dateFormater1.get());
    }

    /**
     * 获取日期的年份
     *
     * @param date YYYY-MM-DD
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String[] getYMD(String date) {
        String[] strs = date.split("-");
        return strs;
    }

    public static Date toDate(String sdate, SimpleDateFormat dateFormater) {
        try {
            return dateFormater.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 判断用户的设备时区是否为东八区（中国） 2014年7月31日
     *
     * @return
     */
    public static boolean isInEasternEightZones() {
        boolean defaultVaule = true;
        if (TimeZone.getDefault() == TimeZone.getTimeZone("GMT+08"))
            defaultVaule = true;
        else
            defaultVaule = false;
        return defaultVaule;
    }

    /**
     * 根据不同时区，转换时间 2014年7月31日
     *
     * @param date
     * @param oldZone
     * @param newZone
     * @return
     */
    public static Date transformTime(Date date, TimeZone oldZone, TimeZone newZone) {
        Date finalDate = null;
        if (date != null) {
            int timeOffset = oldZone.getOffset(date.getTime()) - newZone.getOffset(date.getTime());
            finalDate = new Date(date.getTime() - timeOffset);
        }
        return finalDate;
    }

    /**
     * 获取指定日期是星期几 (1-7)
     * 参数为null时表示获取当前日期是星期几
     *
     * @param date
     * @return
     */
    public static int getWeekOfDate(Date date) {

        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        w = w == 0 ? 7 : w;
        return w;
    }

    /**
     * 获取指定日期是星期几
     * 参数为null时表示获取当前日期是星期几
     *
     * @param date
     * @return
     */
    public static String getWeekOfDateStr(Date date) {
        String[] weekOfDays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        return weekOfDays[getWeekOfDate(date) - 1];
    }

}
